﻿using System;

class KElementsMaxSum
{
    static void Main(string[] args)
    {
        //Exercise 6.
        //Write a program that reads two integer numbers N and K and an array of N elements from the console. 
        //Find in the array those K elements that have maximal sum.

        //enter the length and the elements of the array from the console
        Console.Write("Type the length of the array (N):  ");
        int N = int.Parse(Console.ReadLine());
        Console.WriteLine("Type the elements of the array:");
        int[] array = new int[N];
        for (int i = 0; i < N; i++)
        {
            array[i] = int.Parse(Console.ReadLine());
        }

        //enter K
        Console.Write("Type number of element having maximal sum (K): ");
        int K = int.Parse(Console.ReadLine());

        int sum = 0;
        int bestSum = 0;
        int index = -1;             //index of the first element from the required K elements

        if (K < N)                  //validation for K < N
        {
            for (int i = 0; i < N; i++)
            {
                if (i + K <= N)     //validation if we are still within the array / otherwise - break
                {
                    sum = 0;
                    for (int j = i; j < i + K; j++)     // sum each set of K subsequent elements 
                    {
                        sum += array[j];                      
                    }
                    if (sum > bestSum)
                    {
                        bestSum = sum;
                        index = i;
                    }
                }
                else
                {
                    break;
                }                
            }
            Console.WriteLine();
            Console.Write("The {0} elements that have the maximal sum of {1} are: ", K, bestSum);
            for (int i = 0; i < K; i++)                 //print the numbers themselves
            {
                Console.Write(array[index + i] + " ");                     
            }
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine("Invalid number!");
        }

    }
}

